<?
require_once(dirname(__FILE__).'/../models/Categories.php');

class CategoriesController extends Main_Controller_Action {
	public function preDispatch()
    {
        if (!unserialize(Zend_Auth::getInstance()->getIdentity())->getIsAdministrator()) {        
                $this->_helper->redirector('', '');
        } else {
           
               /**
			 * Translation - Loading dictionaries common and backoffice_common
			 */
			$commonLocale = Translator::loadTranslation($this->currentLang, 'common');
			$this->view->commonLocale = $commonLocale;
        }
    }
	function indexAction(){
		try{
                $this->view->categories = ModelMapper::instance('Categories')->findAll();
                } catch (DatabaseException $e){
                        $e->getMessage();
		}
		
	}
	function addAction(){
		try {
			$categories = ModelMapper::instance('Categories')->findAll();
		} catch (DatabaseException $e){
			$e->getMessage();
		}
		
		$smarty = $this->view->getEngine();

		$this->view->categories = $categories;
		$tpl = $smarty->fetch('categories/add.tpl');
		
		$this->getResponse()->setHeader('Content-Type', 'text/html')->appendBody($tpl);
		$this->getResponse()->sendResponse();
		exit();
	}
	
	function editAction(){
		try {
			$categories = ModelMapper::instance('Categories')->findAll();
		} catch (DatabaseException $e){
			$e->getMessage();
		}
		$category = ModelMapper::instance('Categories')->find(intval($this->getRequest()->getParam('categoryId')));
		
		$smarty = $this->view->getEngine();
		
		$this->view->categories = $categories;
		$this->view->category = $category;
		
		$tpl = $smarty->fetch('categories/edit.tpl');
		
		$this->getResponse()->setHeader('Content-Type', 'text/html')->appendBody($tpl);
		$this->getResponse()->sendResponse();
		exit();
	}
	
	function saveAction(){
		Database::instance()->getConn()->debug =1;
		$formData = $this->_request->getParam('addForm');
		
		if (intval($formData['categoryId']) >0)
			$dCategory = ModelMapper::instance('Categories')->find(intval($formData['categoryId']));
		else
			$dCategory = new Categories();
		
		$dCategory->setCategory(trim(strip_tags(stripcslashes($formData['category']))));
		$dCategory->setParentId($formData['parentId']);
		$dCategory->setWeight(1);
		$dCategory->setLevel($formData['parentId']!='NULL'?1:0);
		

		exit();
	}
	
	function deleteAction(){
		$obj = ModelMapper::instance('Categories')->find(intval($this->getRequest()->getParam('categoriesId')));
		$obj->delete();
		
		exit();
	}
}

	
?>
